package com.jh.paymentchannel.helipay.service;

import java.net.URI;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import com.jh.paymentchannel.helipay.util.HeliPayBase;
import com.jh.paymentchannel.helipay.vo.QueryOrderVo;
import com.jh.paymentchannel.service.AutomaticRepaymentTaskService;
import com.jh.paymentchannel.service.SpendService;
import com.jh.paymentchannel.util.Util;

import cn.jh.common.utils.CommonConstants;
import net.sf.json.JSONObject;

@EnableScheduling
@Configuration
public class XF_TaskService {
	@Autowired
	Util util;

	@Value("${schedule-task.on-off}")
	private String scheduleTaskOnOff;
	@Autowired
    HLRegisterService hlr;
    @Autowired
    SpendService ss;
    @Autowired
    AutomaticRepaymentTaskService arts;
    @Autowired
    QuickPayApi qp;
	private static final Logger log = LoggerFactory.getLogger(XF_TaskService.class);

	/* 8~23点每5分钟执行一次 */
	@Scheduled(cron = "0 0/5 8-23 * * ?")
	public void theWayOnXF() {
		/* 获取开始到结束的五分钟时间段[00:00:00~00:04:00] */
		if ("true".equals(scheduleTaskOnOff)) {
			Date date = new Date();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
			String start = sdf.format(date);
			//String mm = start.substring(15, 16);
			long millistimes = date.getTime();
			//if (mm.contains("1") || mm.contains("6"))
			millistimes -= 240000;
			Calendar calendar = Calendar.getInstance();
			calendar.setTimeInMillis(millistimes);
			start = sdf.format(calendar.getTime());
			calendar.setTimeInMillis(millistimes + 480000);
			String end = sdf.format(calendar.getTime());
			/* 根据执行时间查询任务 */
			log.info("=========================="+start+"--"+end+"===========================");
			Object result = ss.querySpendsbyTime(start, end);
			JSONObject jsonObject = JSONObject.fromObject(result);
			log.info("=========================="+jsonObject+"===========================");
			List<JSONObject> list = null;
			if (jsonObject.containsKey("result")) {
				list = (List) jsonObject.get("result");
			} else {
				return;
			}

			for (int i = 0; i < list.size(); i++) {
				JSONObject art = list.get(i);
				String P5_orderId = art.getString("orderCode");
				String P3_userId = art.getString("userId");
				String P4_bindId = art.getString("bindId");
				String amount = art.getString("amount");
				String payCard = art.getString("payCard");
				String id = art.getString("id");
				/* 根据bindid查询用户到账卡号、手机号 */
				result = hlr.findSFAuthByPhone("", P4_bindId, "");
				jsonObject = JSONObject.fromObject(result);
				log.info("=========================="+jsonObject+"===========================");
				String bankCard = null;
				String phone = null;
				String loginPhone = null;
				if (jsonObject.containsKey("result")) {
					JSONObject jobj = jsonObject.getJSONObject("result");
					bankCard = jobj.getString("bankCard");
					phone = jobj.getString("phone");
					loginPhone = jobj.getString("loginPhone");
				} else {
				}
				/* 根据userid查询用户贴牌 */
				RestTemplate restTemplate = new RestTemplate();
				URI uri = util.getServiceUrl("user", "error url request!");
				String url = uri.toString() + "/v1.0/user/find/by/userid";
				MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
				requestEntity.add("userId", P3_userId);
				result = restTemplate.postForObject(url, requestEntity, String.class);
				log.info("接口/v1.0/user/find/by/userid--RESULT================" + result);
				jsonObject = JSONObject.fromObject(result);
				String brandId = null;
				if (jsonObject.containsKey("result")) {
					JSONObject jobj = jsonObject.getJSONObject("result");
					brandId = jobj.getString("brandId");
				} else {
				}
				restTemplate = new RestTemplate();
				uri = util.getServiceUrl("facade", "error url request!");
				url = uri.toString() + "/v1.0/facade/topup";
				log.info("==============" + url + "===============");
				requestEntity = new LinkedMultiValueMap<String, String>();
				requestEntity.add("phone", loginPhone);
				requestEntity.add("amount", amount);
				requestEntity.add("channe_tag", "HL_PAY");
				requestEntity.add("order_desc", "信用卡消费任务");
				requestEntity.add("brand_id", brandId);
				requestEntity.add("bank_card", payCard);
				requestEntity.add("auth_code", id);
				log.info("接口/v1.0/facade/topup--参数================" + requestEntity);
				result = restTemplate.postForObject(url, requestEntity, String.class);
				log.info("接口/v1.0/facade/topup--RESULT================" + result);
				jsonObject = JSONObject.fromObject(result);
				String orderson = jsonObject.getString("order");
				result = ss.addorderson(P5_orderId, amount, orderson);
				log.info("=========================="+result+"===========================");
				if (CommonConstants.SUCCESS.equals(jsonObject.get("resp_code"))) {
					log.info("接口/v1.0/paymentchannel/spend/update/byordercode--RESULT================" + result);
					result = ss.updateSpendsByOrderCodeAndAmount(P5_orderId, String.valueOf(amount), "成功", "3");
					log.info("=========================="+result+"===========================");

					QueryOrderVo qov = new QueryOrderVo();
    				qov.setP1_bizType("QuickPayQuery");
    				qov.setP2_orderId(orderson);
    				qov.setP3_customerNumber(HeliPayBase.MERCHANT_NO);
    				result = qp.queryOrder("QuickPayQuery", orderson, HeliPayBase.MERCHANT_NO, qov);
    				jsonObject = JSONObject.fromObject(result);
    				/*if ("订单查询成功".equals(jsonObject.getString("message"))) {
						JSONObject jsonObj = jsonObject.getJSONObject("json");
						if ("0000".equals(jsonObj.getString("rt2_retCode"))) {
							if (jsonObj.containsKey("rt7_orderStatus")) {
								
								 * INIT已接收 DOING处理中 SUCCESS成功 FAIL失败 REFUND退款
								 
								if ("SUCCESS".equalsIgnoreCase(jsonObj.getString("rt7_orderStatus"))) {
									result = ss.updateSpendsByOrderCodeAndAmount(P5_orderId, String.valueOf(amount), "成功", "3");
									log.info("=========================="+result+"===========================");
									continue;
								}
								if("INIT".equalsIgnoreCase(jsonObj.getString("rt7_orderStatus"))) {
									result = ss.updateSpendsByOrderCodeAndAmount(P5_orderId, String.valueOf(amount), "已接收，处理中", "5");
									log.info("=========================="+result+"===========================");
									continue;
								}
								if("DOING".equalsIgnoreCase(jsonObj.getString("rt7_orderStatus"))) {
									result = ss.updateSpendsByOrderCodeAndAmount(P5_orderId, String.valueOf(amount), "处理中", "5");
									log.info("=========================="+result+"===========================");
									continue;
								}
								if ("REFUND".equalsIgnoreCase(jsonObj.getString("rt7_orderStatus"))) {
									退款
									result = ss.updateSpendsByOrderCodeAndAmount(P5_orderId, String.valueOf(amount), "退款处理中", "4");
									log.info("=========================="+result+"===========================");
									continue;
								}
							}
						} else {
							if (jsonObj.containsKey("rt7_orderStatus")) {
								if ("REFUND".equalsIgnoreCase(jsonObj.getString("rt7_orderStatus"))) {
									退款
									result = ss.updateSpendsByOrderCodeAndAmount(P5_orderId, String.valueOf(amount), "退款处理中", "4");
									log.info("=========================="+result+"===========================");
									continue;
								}
								if ("FAIL".equalsIgnoreCase(jsonObj.getString("rt7_orderStatus"))) {
									result = ss.updateSpendsByOrderCodeAndAmount(P5_orderId, String.valueOf(amount), "失败", "5");
									log.info("=========================="+result+"===========================");
									continue;
								}
							}
						}
					}else {
						result = ss.updateSpendsByOrderCodeAndAmount(P5_orderId, String.valueOf(amount), "订单查询失败", "5");
						log.info("=========================="+result+"===========================");
						continue;
					}*/
				
				} else {
					if (jsonObject.containsKey("resp_message") && !"".equals(jsonObject.getString("resp_message"))) {
						if ("502".equals(jsonObject.getString("resp_message"))||jsonObject.getString("resp_message").contains("异常")||jsonObject.getString("resp_message").contains("处理")) {
							QueryOrderVo qov = new QueryOrderVo();
            				qov.setP1_bizType("QuickPayQuery");
            				qov.setP2_orderId(orderson);
            				qov.setP3_customerNumber(HeliPayBase.MERCHANT_NO);
            				result = qp.queryOrder("QuickPayQuery", orderson, HeliPayBase.MERCHANT_NO, qov);
            				jsonObject = JSONObject.fromObject(result);
            				if ("订单查询成功".equals(jsonObject.getString("message"))) {
        						JSONObject jsonObj = jsonObject.getJSONObject("json");
        						if ("0000".equals(jsonObj.getString("rt2_retCode"))) {
        							if (jsonObj.containsKey("rt7_orderStatus")) {
        								/*
        								 * INIT已接收 DOING处理中 SUCCESS成功 FAIL失败 REFUND退款
        								 */
        								if ("SUCCESS".equalsIgnoreCase(jsonObj.getString("rt7_orderStatus"))) {
        									result = ss.updateSpendsByOrderCodeAndAmount(P5_orderId, String.valueOf(amount), "成功", "3");
        									log.info("=========================="+result+"===========================");
        									continue;
        								}
        								if("INIT".equalsIgnoreCase(jsonObj.getString("rt7_orderStatus"))) {
        									result = ss.updateSpendsByOrderCodeAndAmount(P5_orderId, String.valueOf(amount), "已接收，处理中", "5");
        									log.info("=========================="+result+"===========================");
        									continue;
        								}
        								if("DOING".equalsIgnoreCase(jsonObj.getString("rt7_orderStatus"))) {
        									result = ss.updateSpendsByOrderCodeAndAmount(P5_orderId, String.valueOf(amount), "处理中", "5");
        									log.info("=========================="+result+"===========================");
        									continue;
        								}
        								if ("REFUND".equalsIgnoreCase(jsonObj.getString("rt7_orderStatus"))) {
        									/*退款*/
        									result = ss.updateSpendsByOrderCodeAndAmount(P5_orderId, String.valueOf(amount), "退款处理中", "4");
        									log.info("=========================="+result+"===========================");
        									continue;
        								}
        							}
        						} else {
        							if (jsonObj.containsKey("rt7_orderStatus")) {
        								if ("REFUND".equalsIgnoreCase(jsonObj.getString("rt7_orderStatus"))) {
        									/*退款*/
        									result = ss.updateSpendsByOrderCodeAndAmount(P5_orderId, String.valueOf(amount), "退款处理中", "4");
        									log.info("=========================="+result+"===========================");
        									continue;
        								}
        								if ("FAIL".equalsIgnoreCase(jsonObj.getString("rt7_orderStatus"))) {
        									result = ss.updateSpendsByOrderCodeAndAmount(P5_orderId, String.valueOf(amount), "失败", "5");
        									log.info("=========================="+result+"===========================");
        									continue;
        								}
        							}
        						}
        					}else {
        						result = ss.updateSpendsByOrderCodeAndAmount(P5_orderId, String.valueOf(amount), "订单查询失败", "5");
								log.info("=========================="+result+"===========================");
								continue;
        					}
            				result = ss.updateSpendsByOrderCodeAndAmount(P5_orderId, String.valueOf(amount), jsonObject.getString("resp_message"), "3");
            				log.info("=========================="+result+"===========================");
							continue;
						}
						result = ss.updateSpendsByOrderCodeAndAmount(P5_orderId, String.valueOf(amount), jsonObject.getString("resp_message"), "5");
        				log.info("=========================="+result+"===========================");
						continue;
					}
					result = ss.updateSpendsByOrderCodeAndAmount(P5_orderId, String.valueOf(amount), "失败原因不明", "5");
    				log.info("=========================="+result+"===========================");
				}
			}
		}
	}
}
